package cn.xiaoliu.user.service.impl;

import cn.xiaoliu.basic.constant.LoginConstant;
import cn.xiaoliu.basic.exception.BusinessException;
import cn.xiaoliu.basic.service.impl.BaseServiceImpl;
import cn.xiaoliu.basic.utils.MD5Utils;
import cn.xiaoliu.basic.utils.StrUtils;
import cn.xiaoliu.org.mapper.EmployeeMapper;
import cn.xiaoliu.user.domain.Logininfo;
import cn.xiaoliu.user.domain.User;
import cn.xiaoliu.user.dto.UserDto;
import cn.xiaoliu.user.mapper.LogininfoMapper;
import cn.xiaoliu.user.mapper.UserMapper;
import cn.xiaoliu.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 业务层实现
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;

    //1.基础的crud通过继承获取

    //2.扩展的方法需要自己写

    @Override
    public void register(UserDto dto) {
        //一.校验所有的参数都不能为空
        if (StringUtils.isEmpty(dto.getPhone())
                || StringUtils.isEmpty(dto.getVerifyCode())
                || StringUtils.isEmpty(dto.getPassword())
                ||StringUtils.isEmpty(dto.getConfirmPassword())){
            throw new BusinessException("请输入所有的信息，信息不能为空");
        }
        //二.手机号不能被注册
        User userTmp = userMapper.loadByPhone(dto.getPhone());
        if (userTmp != null){
            throw new BusinessException("手机号已经被注册，请直接登录");
        }
        //三.校验密码和确认密码一致
        if (!dto.getPassword().equals(dto.getConfirmPassword())){
            throw new BusinessException("两次密码不一致");
        }
        //四.校验验证码是否有效
        Object codeTmp = redisTemplate.opsForValue().get(LoginConstant.PHONE_REGISTER + dto.getPhone());
        if (codeTmp == null){
            throw new BusinessException("验证码已经失效，请重新获取");
        }
        //五.验证码是否一致不区分大小写
        String yzm = codeTmp.toString().split(":")[0];
        if (!dto.getVerifyCode().equalsIgnoreCase(yzm)){
            throw new BusinessException("验证码错误");
        }
        //六.保存数据 先保存t_logininfo再保存t_user
        //1.保存loginginfo
        User user = userDto2User(dto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);//记住返回自增id
        //2.保存user
        user.setLogininfo_id(logininfo.getId());
        userMapper.save(user);
    }

    /**
     * user转为logininfo
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //按照相同的名字拷贝属性
        BeanUtils.copyProperties(user,logininfo );
        logininfo.setType(1);//注意（一定要设置）前端用户注册
        return logininfo;
    }

    /**
     * 将dto转换为user对象
     * @param dto
     * @return
     */
    private User userDto2User(UserDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        //盐值
        String salt = StrUtils.getComplexRandomString(32);
        //密码
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }
    //需要级联修改Logininfo
    @Override
    public void update(User user) {
        super.update(user);
    }

    @Override
    public void remove(Long id) {
        super.remove(id);
    }
}
